 package com.pansky.integration.common.utils;
 
 import java.io.PrintStream;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Date;
 
 public class WorkDayUtils
 {
   public static void main(String[] args)
   {
     try
     {
       String strDateStart = "2013-08-01";
       String strDateEnd = "2014-08-31";
 
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
       Date date_start = sdf.parse(strDateStart);
       Date date_end = sdf.parse(strDateEnd);
       WorkDayUtils app = new WorkDayUtils();
       Calendar cal_start = Calendar.getInstance();
       Calendar cal_end = Calendar.getInstance();
       cal_start.setTime(date_start);
       cal_end.setTime(date_end);
       System.out.println("开始日：" + cal_start.get(1) + "-" + (cal_start.get(2) + 1) + "-" + cal_start.get(5) + " " + app.getChineseWeek(cal_start));
 
       System.out.println("结束日：" + cal_end.get(1) + "-" + (cal_end.get(2) + 1) + "-" + cal_end.get(5) + " " + app.getChineseWeek(cal_end));
 
       System.out.println("工作日：" + app.getWorkingDay(cal_start, cal_end));
       System.out.println("休息日：" + app.getHolidays(cal_start, cal_end));
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 
   public int getDaysBetween(Calendar d1, Calendar d2)
   {
     if (d1.after(d2)) {
       Calendar swap = d1;
       d1 = d2;
       d2 = swap;
     }
     int days = d2.get(6) - d1.get(6);
 
     int y2 = d2.get(1);
     if (d1.get(1) != y2) {
       d1 = (Calendar)d1.clone();
       do {
         days += d1.getActualMaximum(6);
         d1.add(1, 1);
       }while (d1.get(1) != y2);
     }
     return days;
   }
 
   public int getWorkingDay(Calendar d1, Calendar d2)
   {
     int result = -1;
     if (d1.after(d2)) {
       Calendar swap = d1;
       d1 = d2;
       d2 = swap;
     }
 
     int charge_start_date = 0;
     int charge_end_date = 0;
 
     int stmp = 7 - d1.get(7);
     int etmp = 7 - d2.get(7);
     if ((stmp != 0) && (stmp != 6)) {
       charge_start_date = stmp - 1;
     }
     if ((etmp != 0) && (etmp != 6)) {
       charge_end_date = etmp - 1;
     }
 
     result = getDaysBetween(getNextMonday(d1), getNextMonday(d2)) / 7 * 5 + charge_start_date - charge_end_date;
 
     return result;
   }
 
   public String getChineseWeek(Calendar date)
   {
     String[] dayNames = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
     int dayOfWeek = date.get(7);
 
     return dayNames[(dayOfWeek - 1)];
   }
 
   public Calendar getNextMonday(Calendar date)
   {
     Calendar result = null;
     result = date;
     do {
       result = (Calendar)result.clone();
       result.add(5, 1);
     }while (result.get(7) != 2);
     return result;
   }
 
   public int getHolidays(Calendar d1, Calendar d2)
   {
     return getDaysBetween(d1, d2) - getWorkingDay(d1, d2);
   }
 }




